<?php
/**
 * [打印订单]
 * @param  [type] $order [description]
 * @param  [type] $shop  [description]
 * @return [type]        [description]
 */
function print_order($order, $shop)
{
  Vendor("Yprint.Print");

  if ($shop && $shop['print_num'] > 0 && $order['children']) {
    $print = new \Yprint();

    $api_key = '';

    $products_content = '<table><tr><td> 名称 </td><td> 数量 </td><td> 单价 </td></tr>';
    foreach ($order['children'] as $key => $value) {
      $products_content .= "<tr><td> {$value['product_name']} </td><td>{$value['product_num']} </td><td> {$value['product_price']} </td></tr>";
    }
    $products_content .= '</table>';
    $order['created_at'] = date('Y-m-d H:i:s', $order['created_at']);

    if ($shop['print_num'] > 1) {
      $ticket = "<MN>{$shop[print_num]}</MN>";
    } else {
      $ticket = '';
    }

    $ticket .= "<center>@@2{$shop[name]}</center>\n
      订单号：{$order[tran_no]}
      下单时间：{$order[created_at]}\n
      ================================
      {$products_content}
      ================================
      <right>合计：$order[total_amount]元</right>\n";

    if ($order['delivery_types'] == '3') {
      $appointment_time  = date('Y-m-d H:i:s', $order['appointment_time']);
      $ticket .= "================================\n
      联系人：{$order[receiver_name]}\n
      联系电话：{$order[receiver_mobile]}\n
      预订人数：{$order[people]} 人\n
      到店时间：{$appointment_time}\n
      备注：{$order[remark]}";
    }

    if ($order['delivery_types'] == '1') {
      $addr = "{$order[province]} {$order[city]} {$order[area]} {$order[addr]}";
      $ticket .= "================================\n
      联系人：{$order[receiver_name]}\n
      联系电话：{$order[receiver_mobile]}\n
      联系地址：$addr";
    }

    return $print->action_print(5253, $shop['print_code'], $ticket, $api_key, $shop['print_secret']);
  }

  return false;
}

function send_payed_message_to_shop($order)
{
  if (!$order) {
    return false;
  }

  $business = M('users')->field('openid, app_id, phone')->where("shop_id={$order['shop_id']}")->find();
  $app_info = M('apps')->where("id={$business['app_id']}")->find();
  // $buyer = M('users')->field('nickname')->where("id={$order['user_id']}")->find();

  if (!$business) {
    return false;
  }

  $sms_config = D('apps')->get_sms_config($app_info['id']);

  if ($sms_config['sms_type'] == 2) {
    Vendor('AliyunSms.SmsApi');
    $sms = new \SmsApi($sms_config['appkey'], $sms_config['secretKey']);

    $response = $sms->sendSms(
      $sms_config['signname'],
      $sms_config['ordertemplatecode'],
      $business['phone'],
      array(
        "orderno" => $order['tran_no']
      ));
  } else {
    Vendor("alisend.TopClient");
    $c = new \TopClient;
    $c->appkey = $sms_config['appkey'];
    $c->secretKey = $sms_config['secretKey'];
    $req = new \AlibabaAliqinFcSmsNumSendRequest;
    /*$req->setExtend("123456");*/
    $req->setSmsType("normal");
    $req->setSmsFreeSignName($sms_config['signname']);

    $par['orderno'] = $order['tran_no'];
    // $par['name'] = $app_info['name'];
    $par = json_encode($par);

    $req->setSmsParam($par);
    $req->setRecNum($business['phone']);
    $req->setSmsTemplateCode($sms_config['ordertemplatecode']);
    $resp = $c->execute($req);

    $response = (array)($resp);
  }

  return $response;
}

//发送短信给退款申请的商铺
function send_order_refund_msg_to_shop($order)
{
  if (!$order) {
    return false;
  }

  $business = M('users')->field('app_id, phone')->where("shop_id={$order['shop_id']}")->find();
  $app_info = M('apps')->where("id={$business['app_id']}")->find();
  // $buyer = M('users')->field('nickname')->where("id={$order['user_id']}")->find();

  if (!$business) {
    return false;
  }

  $sms_config = D('apps')->get_sms_config($app_info['id']);

  if ($sms_config['sms_type'] == 2) {
    Vendor('AliyunSms.SmsApi');
    $sms = new \SmsApi($sms_config['appkey'], $sms_config['secretKey']);

    $response = $sms->sendSms(
      $sms_config['signname'],
      $sms_config['refundtemplatecode'],
      $business['phone'],
      array(
        "orderno" => "r{$order['tran_no']}"
      ));
  } else {
    Vendor("alisend.TopClient");
    $c = new \TopClient;
    $c->appkey = $sms_config['appkey'];
    $c->secretKey = $sms_config['secretKey'];
    $req = new \AlibabaAliqinFcSmsNumSendRequest;
    /*$req->setExtend("123456");*/
    $req->setSmsType("normal");
    $req->setSmsFreeSignName($sms_config['signname']);

    $par['orderno'] = "r{$order['tran_no']}";
    // $par['name'] = $app_info['name'];
    $par = json_encode($par);

    $req->setSmsParam($par);
    $req->setRecNum($business['phone']);
    $req->setSmsTemplateCode($sms_config['refundtemplatecode']);
    $resp = $c->execute($req);

    $response = (array)($resp);
  }

  return $response;
}

//发送点赞成功短信给商铺
function send_zan_win_message_to_shop($zan)
{
  if (!$zan) {
    return false;
  }
  $product = M('products')->field('name, shop_id')->where("id={$zan['product_id']}")->find();
  $business = M('users')->field('openid, app_id, phone')->where("shop_id={$product['shop_id']}")->find();
  $user = M('users')->field('nickname')->where("id={$zan['user_id']}")->find();

  if (!$product || !$business || !$user) {
    return false;
  }

  $sms_config = D('apps')->get_sms_config($business['app_id']);

  if ($sms_config['sms_type'] == 2) {
    Vendor('AliyunSms.SmsApi');
    $sms = new \SmsApi($sms_config['appkey'], $sms_config['secretKey']);

    $response = $sms->sendSms(
      $sms_config['signname'],
      $sms_config['zanwintemplatecode'],
      $business['phone'],
      array(
        "nickname" => "{$user['nickname']}",
        "productname" => "{$product['name']}"
      ));
  } else {
    Vendor("alisend.TopClient");
    $c = new \TopClient;
    $c->appkey = $sms_config['appkey'];
    $c->secretKey = $sms_config['secretKey'];
    $req = new \AlibabaAliqinFcSmsNumSendRequest;
    /*$req->setExtend("123456");*/
    $req->setSmsType("normal");
    $req->setSmsFreeSignName($sms_config['signname']);

    $par['productname'] = "{$product['name']}";
    $par['nickname'] = "{$user['nickname']}";
    // $par['name'] = $app_info['name'];
    $par = json_encode($par);

    $req->setSmsParam($par);
    $req->setRecNum($business['phone']);
    $req->setSmsTemplateCode($sms_config['zanwintemplatecode']);
    $resp = $c->execute($req);

    $response = (array)($resp);
  }

  return $response;
}

function is_cli_request()
{
  return (php_sapi_name() === 'cli' or defined('STDIN'));
}

function random_filename($path = 'upload')
{
  $savename = md5(uniqid()).'.png';
  $tmp_name = "{$path}/{$savename}";

  return array('savename' => $savename, 'tmp_name' => $tmp_name);
}

/**
 * [保存图片文件]
 * @param  [type] $url [description]
 * @return [type]      [description]
 */
function save_img($url)
{
  $url = trim($url);
  if (!$url) {
    return false;
  }

  ob_start();
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  $response = curl_exec($ch);

  $file = random_filename();
  $result = file_put_contents($file['tmp_name'], ob_get_contents());

  curl_close($ch);
  ob_end_clean();

  if ($result) {
    return $file;
  }

  return false;
}

function get_product_wxacode($product, $app_id, $debug_token = false)
{
  if (!$product) {
    return false;
  }

  if ($debug_token) {
    $xcx_token['access_token'] = $debug_token;
    $page = 'pages/index/index';
  } else {
    $xcx_token = load_xcx_token($app_id);
    $page = 'pages/share/share';
  }

  $params = array(
    'width' => 240,
    'auto_color' => false,
    'line_color' => array('r' => 153, 'g' => 153, 'b' => 153),
    'page' => $page,
    'scene' => "pid:{$product['id']}-sid:{$product['shop_id']}"
  );

  ob_start();
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$xcx_token['access_token']}");
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  $response = curl_exec($ch);

  $filename = md5(uniqid()).'.png';
  $tmp_file = "./upload/tmp/{$filename}";
  $file['savepath'] = "products/wxacode/{$month}";
  $file['savename'] = $filename;
  $file['tmp_name'] = $tmp_file;
  $file['type'] = 'image/png';

  $result = file_put_contents($file['tmp_name'], ob_get_contents());
  $check_result = json_decode(ob_get_contents(), true);
  $file['size'] = filesize(THINK_PATH."../{$tmp_file}");

  curl_close($ch);
  ob_end_clean();

  if ($check_result['errcode']) {
    S('xcx_token_'.$app_id, NULL);
    $now_time = date("Y-m-d H:i:s",time());
    file_put_contents('wechat-token.log', "\r\n {$now_time} 海报调用xcx_token_{$app_id}:失效{$check_result['errcode']}{$check_result['errmsg']}", FILE_APPEND);
    return false;
  }

  if ($result) {
    //$url = upload_local_file($app_id, $file);

    return $file;
  }

  return false;
}

function get_product_thumb($product_logo)
{
  $image = new \Think\Image();

  $filename = md5(uniqid()).'.jpg';
  $month = Date('Ym');
  if (!file_exists(THINK_PATH."../upload/watermark/{$month}/")) {
    mkdir(THINK_PATH."../upload/watermark/{$month}/", 0777, true);
  }

  $content = file_get_contents("{$product_logo}!640x640");
  file_put_contents("./upload/tmp/{$filename}", $content);

  $savepath = "./upload/tmp/".md5(uniqid()).'.jpg';
  $result =  $image->open("./upload/source/product-bg.jpg")
  ->water("./upload/tmp/{$filename}", \Think\Image::IMAGE_WATER_NORTHWEST)
  ->save($savepath);

  if ($result) {
    @unlink("./upload/tmp/{$filename}");
    return $savepath;
  }

  return false;
}

function send_withdraw_payed_message_to_shop($log_id)
{
  $log = M('amount_logs')->alias('l')
                         ->join("left join ".C("DB_PREFIX")."shops s on s.id=l.shop_id")
                         ->join("left join ".C("DB_PREFIX")."users u on u.shop_id=s.id")
                         ->join("left join ".C("DB_PREFIX")."apps a on u.app_id=a.id")
                         ->where("l.id=$log_id")
                         ->field('l.*, u.xcx_openid, u.app_id, a.pay_to_shop_template_id')
                         ->find();
  //$date = date('Y-m-d H:i:s', time());
  $params = array(
    'xcx_openid' => $log['xcx_openid'],
    'template_id' => $log['pay_to_shop_template_id'],
    'form_id' => $log['form_id'],
    'data' => array(
      'keyword1' => array('value' => "{$log['amount']}元", 'color' => '#173177'),
      'keyword2' => array('value' => '请到小程序提现结算明细下查看。', 'color' => '#173177'),
    ),
    'page' => 'pages/shop/withdraw'
  );

  $result = send_app_msg($params, $log['app_id']);
}
